from urllib import request,parse
import json


def translate(keyword):
    
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
    #定义请求的参数，并编码转换
    data = {
        'i':keyword,
        'doctype':'json',
    }
    data = parse.urlencode(data)

    #设置headers头信息
    headers = {
        'Content-Length':len(data),
    }

    try:
        #创建请求
        req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)

        #爬取信息
        res=request.urlopen(req)

        #解析结果
        str_json = res.read().decode("utf-8")
        myjson = json.loads(str_json)

        print(myjson['translateResult'][0][0]['tgt'])
    except error.URLError as err:
        print(err.reason)

if __name__ == '__main__':
    while True:
        keyword = input("请输入要翻译的语句：")
        if keyword == "q":
            break
        else:
            print("翻译结果为：")
            translate(keyword)
        


